# -*- coding： UTF-8 -*-
from util.math.MathUtil import  *
class CorrectPaperFactory:

    def __init__(self):
        self.paper = []
        self.result = {"total":0,"correct":0,"wrong":0}
        self.count = 0

    def judgeProblem(self,problemStr):
        #格式如下 1. 1 + 2 + 3 + 4
        a = problemStr.index('.')
        problemIndex =  problemStr[0:a]
        b = problemStr.index('=')
        answer = problemStr[b+1:]
        problem = problemStr[a+1:b]
        expression = []
        for item in problem.split(' '):
            if len(item) < 1: continue
            expression.append(item)

        postExp = transToPostExp(expression)
        correctAns = computePostExpValue(postExp)
        flag,ans = self.compareAnswer(answer,correctAns)

        if flag :
            self.result["correct"] = self.result["correct"] + 1
            self.paper.append(problemStr + " Correct!\r\n")
        else:
            self.result["wrong"] = self.result["wrong"] + 1
            self.paper.append(problemStr + " Wrong! Correct:" +  ans +"\r\n")

        self.count = self.count + 1

    def compareAnswer(self,ansStr,correctAns):
        if type(correctAns) is list:
            return self.compareFractionAnswer(ansStr,correctAns)
        else:
           return True if ansStr.strip() == str(correctAns) else False,str(correctAns)

    def compareFractionAnswer(self,ansStr,correctAns):
        corrAns = ''
        if correctAns[0] == 0:
            # 答案为 分子/分母 整数部分为 0
            corrAns = str(correctAns[1]) + '/' + str(correctAns[2])
        elif correctAns[1] == 0:
            # 答案为整数
            corrAns = str(correctAns[0])
        else:
            corrAns = str(correctAns[0]) + "'"+str(correctAns[1]) + "/"+str(correctAns[2])

        return  True if  ansStr.strip() == corrAns else False,corrAns


    def getPaperAfterCorrect(self):
        return self.paper

    def getResultString(self):
        return "TOTAL: "+str(self.count) + "\r\n" + "CORRECT:" \
               + str(self.result["correct"]) +"\r\n"+"WRONG:"+str(self.result["wrong"])+"\r\n"
